#!E:\Anaconda3\envs\dll\python.exe

print("Content-type:text/html\n")

import pymysql
import implement
import jieba.analyse


def get_conn():
    conn = pymysql.connect(
        host='localhost',
        port=3306,
        user='root',
        passwd='',
        db='lstm_car_comment'
    )
    return conn


def update(sql, args):
    conn = get_conn()
    cur = conn.cursor()
    cur.execute(sql, args)
    conn.commit()
    cur.close()
    conn.close()


def select(sql):
    conn = get_conn()
    cur = conn.cursor()
    cur.execute(sql)
    res = cur.fetchall()
    cur.close()
    conn.close()
    return res


def key_words(data):
    lists = []
    for x in data:
        keywords = " ".join(jieba.analyse.extract_tags(sentence=x[1], topK=1, withWeight=False, allowPOS=()))
        sets = {
            'Pid': x[0],
            'key_words': keywords
        }
        lists.append(sets)

    return lists


# 查询所有未预测和未提取关键字的数据
sql1 = 'select Pid,content from comments where KeyWords IS NULL or Theme IS NULL or Emotional IS NULL'
# sql1 = 'select Pid,content from comments'
result = select(sql1)
# 将二维元组转化为数组
result = list(result)
for x in result:
    result[result.index(x)] = list(x)
# 去除数据末尾的/r/n
for x in result:
    if x[1][-4:] == '/r/n':
        x[1] = x[1][:-4]

# print(result)
# 预测
predict = implement.predict(result)
# print(predict)
# 关键词提取
words = key_words(result)
# print(words)
# 写入数据库
sql2 = "update comments set Theme= %s, Emotional=%s where Pid=%s"
for each in predict:
    args2 = (each.get('Theme'), each.get('Emotional'), each.get('Pid'))
    update(sql2, args2)
sql3 = 'update comments set KeyWords=%s where Pid=%s'
for each in words:
    args3 = (each.get('key_words'), each.get('Pid'))
    update(sql3, args3)
# 返回信息
yhNum, kjNum, dlNum, ckNum, wgNum, nsNum, ssxNum = [0, 0, 0, 0, 0, 0, 0]
for x in predict:
    theme = x.get("Theme")
    if theme == '油耗':
        yhNum += 1
    elif theme == '空间':
        kjNum += 1
    elif theme == '动力':
        dlNum += 1
    elif theme == '操控':
        ckNum += 1
    elif theme == '外观':
        wgNum += 1
    elif theme == '内饰':
        nsNum += 1
    elif theme == '舒适性':
        ssxNum += 1
dic = str(yhNum) + ' ' + str(kjNum) + ' ' + str(dlNum) + ' ' + str(ckNum) + ' ' + str(wgNum) + ' ' + str(
    nsNum) + ' ' + str(ssxNum) + ' '
print(dic)
